/**
 * 组件安装
 */

// 引入 gulp及组件
var gulp = require('gulp'), //基础库
    htmlmin = require('gulp-htmlmin'),
    rename = require('gulp-rename'), //重命名
    concat = require('gulp-concat'), //合并文件
    clean = require('gulp-clean'), //清空文件夹
    replace = require('gulp-replace'), //字符串替换
    uglify = require('gulp-uglify'), //js压缩
    gulpSequence = require('gulp-sequence'),
    fs = require('fs'),
    path = require('path'),
    gulpif = require('gulp-if'),
    cheerio = require('gulp-cheerio'),
    run = require('gulp-run'),
    merge = require('merge-stream'),
    through2 = require('through2'),
    revCollector = require('gulp-rev-collector'),
    deasync = require('deasync'),
    md5 = require('gulp-md5-plus'),
    fileinclude = require('gulp-file-include'),
    zip = require('gulp-zip');
var srcDst = './src/';
var verDst = './ver/';
var relDst = './dist/';
var frontendDst = './frontend/';
var frontendSourceZip = 'ZHK_PRO_APP.zip';
var frontendSourceUrl = 'http://10.200.41.55/' + frontendSourceZip;
var opts;
var cdnUrl;
var isUglify = false;
var nestedSrc = function() {
    var temp = false;
    if (isUglify || process.argv.indexOf('--uglify') !== -1) {
        temp = true;
    }
    return temp
};
var getCNDOpt = function() {
    var opt = [];
    for (var i = 0, length = opts.length; i < length; i++) {
        if (opts[i] !== "" && opts[i].indexOf("=") > -1) {
            opt = opts[i].replace(/\s/g, "").replace('=', '#===#').split('#===#');
            if (String(opt[0]) === 'cdnUrl') {
                cdnUrl = opt[1];
            }
        }
    }
}
var CDN = function() {
    var temp = false;
    if (!!cdnUrl) {
        temp = true;
    }
    return temp;
};
// HTML处理
gulp.task('html', function() {
    var Src = [frontendDst + "ver/**/*.json", srcDst + 'html/**/*.html'],
        Dst = relDst + 'html/';
    return gulp.src(Src)
        .pipe(cheerio({
            run: function($) {
                $('link').remove();
                $('head').append("@@include('../components/header.html')");
                $('script[type!="text/template"]').remove();
                $('body').append("@@include('../components/footer.html')");
            },
            parserOptions: {
                decodeEntities: false
            }
        }))
        .pipe(fileinclude({
            prefix: '@@',
            basepath: '@file'
        }))
        .pipe(revCollector())
        .pipe(modify(replaceOpts))
        .pipe(gulp.dest(Dst));
});
// 样式处理
gulp.task('css', function() {
    var Src = srcDst + 'css/**/*.*',
        Dst = relDst + 'css/';
    return gulp.src(Src)
        .pipe(gulp.dest(Dst));
});
gulp.task('images', function() {
    var Src = srcDst + 'images/**/*.*',
        Dst = relDst + 'images/';
    return gulp.src(Src)
        .pipe(gulp.dest(Dst));
});
//js部分处理
// gulp.task('jsLog', function() {
//     var jsLogSrc = [srcDst + 'js/log/**/*.js'],
//         jsLogDst = relDst + 'js/log/';
//     return gulp.src(jsLogSrc)
//         .pipe(modify(replaceOpts))
//         .pipe(gulpif(nestedSrc, uglify()))
//         .pipe(gulp.dest(jsLogDst));
// });
gulp.task('lib', function() {
    var Src = [srcDst + 'lib/**/*.*'],
        Dst = relDst + 'lib/';
    return gulp.src(Src)
        .pipe(gulp.dest(Dst));
});
gulp.task('md5:js', function(done) {
    gulp.src([relDst + 'js/**/*.js', '!' + relDst + 'js/log/**/*.js'])
        .pipe(md5(10, relDst + 'html/**/*.html'))
        .pipe(gulp.dest(relDst + 'js/'))
        .on('end', done);
});
gulp.task('md5:libcss', function(done) {
    gulp.src(relDst + 'js/lib/**/*.css')
        .pipe(md5(10, relDst + 'html/**/*.html'))
        .pipe(gulp.dest(relDst + 'js/lib/'))
        .on('end', done);
});
//清空图片、样式、js
gulp.task('clean', function() {
    return gulp.src([relDst], {
            read: false
        })
        .pipe(clean({
            force: true
        }));
});
gulp.task('replaceCDN', function() {
    gulp.src(relDst + 'html/**/*.html')
        .pipe(gulpif(CDN, replace('href="../../', 'href="' + cdnUrl)))
        .pipe(gulpif(CDN, replace('src="../../', 'src="' + cdnUrl)))
        .pipe(gulp.dest(relDst + 'html/'))
});
//自定义插件替换方法
function replaceOpts(stream) {
    var temp = [],
        str;
    for (var i = 0, length = opts.length; i < length; i++) {
        if (opts[i] !== "" && opts[i].indexOf("=") > -1) {
            temp = opts[i].replace(/\s/g, "").replace('=', '#===#').split('#===#');
            str = eval('/\\#\\[' + temp[0] + '\\]\\#/g');
            stream = stream.replace(str, temp[1]);
        }
    }
    return stream;
};
//自定义插件modify
function modify(modifier) {
    return through2.obj(function(file, encoding, done) {
        var content = modifier(String(file.contents));
        file.contents = new Buffer(content);
        this.push(file);
        done();
    });
};

function getFolders(dir) {
    var temp, folders = [];
    temp = fs.readdirSync(dir)
        .filter(function(file) {
            return fs.statSync(path.join(dir, file)).isDirectory();
        });
    for (var i = 0, length = temp.length; i < length; i++) {
        if (temp[i] !== 'lib' && temp[i] !== 'log') {
            folders.push(temp[i]);
        }
    }
    return folders;
}

gulp.task('businessJS', function() {
    var folders = getFolders(srcDst + 'js');
    //if (folders.length == 0) {
    return gulp.src([frontendDst + "ver/**/*.json", path.join('./' + srcDst + 'js', '/**/**.js')])
        .pipe(revCollector())
        .pipe(modify(replaceOpts))
        .pipe(concat('main.js'))
        .pipe(gulpif(nestedSrc, uglify()))
        .pipe(gulp.dest(relDst + 'js/'));
    // } else {
    //     var tasks = folders.map(function(folder) {
    //         return gulp.src([frontendDst + "ver/**/*.json", path.join('./' + srcDst + 'js', folder, '/**/**.js')])
    //             .pipe(revCollector())
    //             .pipe(modify(replaceOpts))
    //             .pipe(concat(folder + '.js'))
    //             .pipe(gulpif(nestedSrc, uglify()))
    //             .pipe(gulp.dest(relDst + 'js/'));
    //     });
    //     return merge(tasks);
    // }
});
gulp.task('baseJS', function() {
    return gulp.src([frontendDst + "ver/**/*.json", path.join('./' + srcDst + 'base', '/**/**.js')])
        .pipe(revCollector())
        .pipe(modify(replaceOpts))
        .pipe(concat('base.js'))
        .pipe(gulpif(nestedSrc, uglify()))
        .pipe(gulp.dest(relDst + 'base/'));
});

//获取配置文件
gulp.task('getOptsDev', function() {
    getOpts('./profile/env.properties.dev');
});
gulp.task('getOptsIdc', function() {
    getOpts('./profile/env.properties.idc_product');
    isUglify = true;
});
gulp.task('getOptsTest', function() {
    getOpts('./profile/env.properties.test');
});

function getOpts(src) {
    opts = fs.readFileSync(src, 'utf8').replace(/[\r]/g, "").split("\n");
    getCNDOpt();

};


/*下载前端资源*/
gulp.task('frontend:clean', function() {
    return gulp.src([frontendDst, srcDst + 'css/'], {
            read: false
        })
        .pipe(clean({
            force: true
        }));
});
gulp.task('frontend:download', function() {
    var download = require('gulp-downloader');
    return download({
            request: {
                url: frontendSourceUrl
            }
        })
        .pipe(gulp.dest(frontendDst));
});
gulp.task('frontend:unzip', function() {
    var unzip = require("gulp-unzip");
    /*fs.createReadStream(frontendDst + frontendSourceZip)
        .pipe(unzip.Extract({
            path: frontendDst
        }));
    return require('deasync').sleep(1000);*/
    return gulp.src(frontendDst + frontendSourceZip)
        .pipe(unzip())
        .pipe(gulp.dest(frontendDst))
});

gulp.task('frontend:copyCss', function() {
    return gulp.src(frontendDst + 'css/**/*.*')
        .pipe(gulp.dest(srcDst + 'css/'));
});
gulp.task('frontend:copyImages', function() {
    return gulp.src(frontendDst + 'images/**/*.*')
        .pipe(gulp.dest(srcDst + 'images/'));
});
gulp.task('frontend:copyBase', function() {
    return gulp.src(frontendDst + 'js/**/*.*')
        .pipe(gulp.dest(srcDst + 'base/'));
});
gulp.task('frontend:copyLib', function() {
    return gulp.src(frontendDst + 'lib/**/*.*')
        .pipe(gulp.dest(srcDst + 'lib/'));
});


/*zip*/
function getNeedZipFolders(dir) {
    return fs.readdirSync(dir)
        .filter(function(file) {
            return fs.statSync(path.join(dir, file)).isDirectory();
        });
};

gulp.task('zip', function() {
    var folders = getNeedZipFolders(relDst);
    var tasks = folders.map(function(folder) {
        return gulp.src(path.join(relDst, folder, '/**/**.*'))
            .pipe(rename(
                function(path) {
                    var dirname = path.dirname;
                    path.dirname = folder + '/' + dirname;
                }))
            .pipe(zip(folder + '.zip'))
            .pipe(md5(10))
            .pipe(gulp.dest(relDst));
    });
    return merge(tasks);
});

gulp.task('zipNoMd5', function() {
    var folders = getNeedZipFolders(relDst);
    var tasks = folders.map(function(folder) {
        return gulp.src(path.join(relDst, folder, '/**/**.*'))
            .pipe(rename(
                function(path) {
                    var dirname = path.dirname;
                    path.dirname = folder + '/' + dirname;
                }))
            .pipe(zip(folder + '.zip'))
            //.pipe(md5(10))
            .pipe(gulp.dest(relDst));
    });
    return merge(tasks);
});

gulp.task('downloadFrontendSrc', gulpSequence('frontend:clean', 'frontend:download', 'frontend:unzip', 'frontend:copyCss', 'frontend:copyImages', 'frontend:copyBase', 'frontend:copyLib'));
gulp.task('default', gulpSequence("getOptsIdc", "clean", 'downloadFrontendSrc', 'lib', 'images', 'css', 'businessJS', 'baseJS', 'html', 'replaceCDN', 'zip'));
gulp.task('dev', gulpSequence("getOptsDev", "clean", 'downloadFrontendSrc', 'lib', 'images', 'css', 'businessJS', 'baseJS', 'html', 'replaceCDN', 'zip'));
gulp.task('idc_product', gulpSequence("getOptsIdc", "clean", 'downloadFrontendSrc', 'lib', 'images', 'css', 'businessJS', 'baseJS', 'html', 'replaceCDN', 'zip'));
gulp.task('test', gulpSequence("getOptsTest", "clean", 'downloadFrontendSrc', 'lib', 'images', 'css', 'businessJS', 'baseJS', 'html', 'replaceCDN', 'zip'));
gulp.task('dev:watch', gulpSequence("getOptsDev", "clean", 'downloadFrontendSrc', 'lib', 'images', 'css', 'businessJS', 'baseJS', 'html', 'replaceCDN', 'zipNoMd5', 'watch'));


/*watch */
gulp.task('building', function() {
    var callback = function() {

    };
    gulpSequence("getOptsDev", "clean", 'lib', 'images', 'css', 'businessJS', 'baseJS', 'html', 'replaceCDN', 'zip')(callback);
});
gulp.task('watch', function() {
    gulp.watch([srcDst + '**/**/*.html', srcDst + '**/**/*.js'], ['building']);
});
